Easy
On a staircase, the i
-th step has some non-negative cost cost[i]
assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Example 1:
1 | Input: cost = [10, 15, 20] |
Example 2:
1 | Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] |
Note:
cost
will have a length in the range[2, 1000]
.- Every
cost[i]
will be an integer in the range[0, 999]
.
最近在刷动态规划的题,这篇文章是我写的动态规划一点想法,和大家分享一下
- Dp
1 | class Solution: |
从题目中也可以注意到,有些dp的空间是并不需要的,因为我们只需要关注当前位置的前一个(i-1)和前两个(i-2)所以使用两个变量,完全就足够了。
改良版:
1 | class Solution: |
⚠️注意:
- 由于题目给的note明确说明cost长度大于等于2,所以不用考虑edge case。
- 对题目的理解是否准确,并不是跳到cost的最后就结束了(not range(2, len(cost))),而是要跳出cost (range(2, len(cost)+1))